package com.xujiang.common.ui;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.xujiang.common.util.GlobalStaticVariable;
import com.xujiang.common.util.L;
import com.xujiang.common.util.MBroadcastReceiver;
import com.xujiang.common.util.NetWorkChang;
import com.xujiang.common.util.NetworkUtils;
import com.xujiang.common.util.ToolBarHelper;
import com.xujiang.common.util.UIUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * BaseActivity 负责所有网络变化的监听，以及toolbar的一些设置
 *
 * @author xujiang
 * @version 2017-05-09 16:59
 */
public class BaseActivity extends AppCompatActivity {

    public MBroadcastReceiver mBroadcastReceiver;  //广播接收器

    public ConnectivityManager connectivityManager;  //网络管理器，监听网络变化需要

    private int connectedType;  //网络类型

    private NetWorkChang netWorkChang;    //网络变化回掉

    private String TAG = getActivity().getClass().getSimpleName();

    private ToolBarHelper toolBarHelper; //toolbar 帮助类

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);      //注册eventbus
        mBroadcastReceiver = new MBroadcastReceiver(new MBroadcastReceiver.OnMBroadcastListener() {
            @Override
            public void onReceive(Context context, Intent intent) {
                netChangeCallback(intent);   //当收到网络变化的广播时进行的处理
            }
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");   //网络变化的广播action
        mBroadcastReceiver.registerBroadcastReceiver(getApplicationContext(), mBroadcastReceiver,
                intentFilter);  //注册广播接收器
        GlobalStaticVariable.BroadcastReceiverNum = 1;          //每次注册时 会接收到一条广播，此数值表示接受到广播不处理,0表示要处理

    }

    private void netChangeCallback(Intent intent) {
        String action = intent.getAction(); //当前接受到的广播的标识(行动/意图)
        // 当当前接受到的广播的标识(意图)为网络状态的标识时做相应判断
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  //此处只对网络改变的广播进行处理
            connectivityManager = NetworkUtils.getConnManager(BaseActivity.this);  //获取ConnectivityManager连接管理器对象
            connectedType = NetworkUtils.getConnectedType(BaseActivity.this);   //获取网络类型
            if (netWorkChang == null) {
                netWorkChang = new NetWorkChang.EmptyNetWorkChange();  //回掉如果是空，新建一个防止报错，说明继承这个BaseActivity的activity不需要回掉，下面有函数可以对其赋值
            }
            if (connectedType == 1) {  //无网络链接
                //无网络可用
                L.getToast().showLog(BaseActivity.this, "网络失效，无网络可用");
                netWorkChang.isuseless();
            }
            if (connectedType == 2) {   //移动网络
                //移动网络
                boolean mobileConnected = NetworkUtils.isMobileConnected(BaseActivity.this);
                if (mobileConnected) {
                    //有效的链接
                    L.getToast().showLog(BaseActivity.this, "你当前在使用移动网络，请注意流量");
                    netWorkChang.onMOBILE();
                } else {
                    //无效的链接
                    L.getToast().showLog(BaseActivity.this, "你的移动链接无效");
                    netWorkChang.isuseless();
                }
            }
            if (connectedType == 4) {  //wifi
                //wifi
                boolean wifiConnected = NetworkUtils.isWifiConnected(BaseActivity.this);
                if (wifiConnected) {
                    //有效的链接
                    NetworkUtils.isNetWorkAvailable();

                } else {
                    //无效的链接
                    L.getToast().showLog(BaseActivity.this, "wifi链接无效");
                    netWorkChang.isuseless();
                }
            }
            if (connectedType == 8) {  //不知名网络
                //其他网络
                L.getToast().showLog(BaseActivity.this, "其他网络");
                netWorkChang.other();
            }

        }
    }

    /**
     * Eventbas 通过消息传递确认网络联通情况
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(String event) {    //有时链接上wifi，却无法访问外网，通过okhttp访问百度后通过eventbus返回结果，判断网络是否可用
        if (event.equals("true")) {
            L.getToast().showLog(BaseActivity.this, "你已链接上wifi，请放心使用");
            netWorkChang.onWifi();
        } else {
            L.getToast().showLog(BaseActivity.this, "你已链接上wifi是局域网，无法访问外网");
            netWorkChang.onWifi();
        }
    }

    /**
     * 上层activity设置回调监听
     */
    public void setNetworkChangeListener(NetWorkChang networkChange) {
        this.netWorkChang = networkChange;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //广播和eventbus的取消注册
        if (mBroadcastReceiver != null) {
            mBroadcastReceiver.unregisterReceiver(getApplicationContext(), mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);

    }

    /*****************************************************************************************/
    /**
     * 以下为Toolbar的设置
     */

    /**
     * actionbar的设置，返回按钮
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            //onBackPressed();
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public ToolBarHelper getToolBarHelper() {
        return toolBarHelper;
    }

    public Toolbar getToolbar() {
        return toolBarHelper.getToolbar();
    }

    //自定义的title
    public void setMTitle(CharSequence title) {
        if (toolBarHelper.getToolbarTitle() != null && title != null) {
            toolBarHelper.getToolbarTitle().setText(title);
        }
    }

    //将自定义title设置成可见，同时可以设置一个title
    public void setTitle(String title) {
        toolBarHelper.setToolbarTitleVisibility(true);
        toolBarHelper.setToolbarTitle(title);
    }

    public void setSubTitle(String title) {
        toolBarHelper.setToolbarSubTitleVisibility(true);
        toolBarHelper.setToolbarSubTitle(title);
    }

    public void setToolBarleft(@NonNull int resid) {
        toolBarHelper.setToolbarLeft(true);
        toolBarHelper.setToolbarLeft(resid);
    }

    public void setToolBarRight(@NonNull int resid) {
        toolBarHelper.setToolbarRight(true);
        toolBarHelper.setToolbarRight(resid);
    }

    public String getMTitle() {
        if (toolBarHelper.getToolbarTitle() == null) {
            return "";
        }
        return toolBarHelper.getToolbarTitle().getText().toString();
    }

    //初始化toolbar，同时设置title可见
    protected void initToolBarshowTitleforLable() {
        initToolBar();
        toolBarHelper.setToolbarTitleVisibility(true);
    }

    protected void initToolBar() {
        toolBarHelper = initToolBar((AppCompatActivity) getActivity());
    }

    protected ToolBarHelper initToolBar(AppCompatActivity activity) {
        if (activity == null) {
            return null;
        }
        return ToolBarHelper.with(activity);
    }

    protected void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    public View inflate(@LayoutRes int resource) {
        return UIUtils.inflate(getActivity(), resource);
    }

    public View inflate(@LayoutRes int resource, ViewGroup root) {
        return UIUtils.inflate(getActivity(), resource, root);
    }

    public View inflate(@LayoutRes int resource, ViewGroup root, boolean attachToRoot) {
        return UIUtils.inflate(getActivity(), resource, root, attachToRoot);
    }

    public View findViewById(@NonNull View view, @IdRes int resource) {
        return UIUtils.findViewById(view, resource);
    }

    public ActionBar getBaseActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar == null) {
            throw new AndroidRuntimeException("getSupportActionBar is null");
        }
        return actionBar;
    }

    public Activity getActivity() {
        return this;
    }

    /**
     * 设置titile时调用
     */
    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        if (toolBarHelper == null) {
            return;
        }
        if (!TextUtils.isEmpty(getMTitle()) || TextUtils.isEmpty(title)) {
            return;
        }
        if (UIUtils.isVisible(toolBarHelper.getToolbarTitle())) {
            setMTitle(title.toString());
        }
    }

    /*************         通知的相关操作           *************************/

    public NotificationManager mNotificationManager;


    /**
     * Notification为通知信息类，它里面对应了通知栏的各个属性
     * NotificationManager ：  是状态栏通知的管理类，负责发通知、清除通知等操作。
     * 注意：NotificationManager 是一个系统Service，所以必须通过 
     * getSystemService(NOTIFICATION_SERVICE)方法来获取，
     */

    /**Notification 的管理类  使用前请调用初始化 */
    private void initService() {
        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    }

    /**
     * 清除指定id的通知
     * @param notifyId
     */
    public void clearNotify(int notifyId){
        mNotificationManager.cancel(notifyId);  //);//消除对应ID的通知
    }

    /**
     * 清楚创建的所有通知
     */
    public void clearAllNotify(){
        mNotificationManager.cancelAll(); //消除创建的所有通知

    }

    /**
     * pendingIntent  延迟的Intent
     *PendingIntent可以支持三种意图：启动Activity,启动Service，启动Broadcast
     *
     * @param flags
     * @return
     */
    public PendingIntent getDefalutIntent(int flags){
        PendingIntent pendingIntent = PendingIntent.getActivity(this,1,new Intent(),flags);
        return pendingIntent;
    }
}
